package tech.moya.flexbase.dao
{
	import flash.data.SQLColumnSchema;
	import flash.data.SQLConnection;
	import flash.data.SQLSchemaResult;
	import flash.data.SQLTableSchema;
	
	import tech.moya.flexbase.beans.Column;
	import tech.moya.flexbase.beans.Connection;
	import tech.moya.flexbase.beans.Table;
	import tech.moya.flexbase.core.BaseContext;
	
	public class TableDAO
	{
		private var context:BaseContext ;
		
		public function TableDAO(cntxt:BaseContext)
		{
			this.context = cntxt;
		}
		
		public function getAllTables():Array{
			var conn:SQLConnection = context.openConnection(); 
			var schemaResult:SQLSchemaResult ;
			var table:SQLTableSchema;
			var tableObj:Table;
			var tablesList:Array = new Array();
			
			conn.loadSchema();
			schemaResult = conn.getSchemaResult();
			
			for (var i:int=0;i<schemaResult.tables.length;++i){
				table = SQLTableSchema(schemaResult.tables[i]);
				tableObj = new Table(table.name,getColumnsArray(table));
				tablesList.push(tableObj);
			}
			context.closeConnection(conn);
			return  tablesList;
		}
		
		private function getColumnsArray(table:SQLTableSchema):Array{
			
			var columnObj:Column;
			var column:SQLColumnSchema;
			var columnList:Array = new Array();
			
			for(var i:int=0;i<table.columns.length;++i){
				column = SQLColumnSchema(table.columns[i]);
				columnObj = new Column(column.name,column.dataType);
				columnList.push(columnObj);
			}
			
			return columnList;	
		}

	}
}